<template>
  <div class="main_left">
      <ul class="main_left_ul" @click="tab">
          <li class="main_left_li" :class="{'active':currenTab=='all'}" data-title='all'>全部商品</li>
          <li class="main_left_li" :class="{'active':currenTab=='seckill'}" data-title='seckill'>秒杀</li>
          <li class="main_left_li" :class="{'active':currenTab=='fruits'}" data-title='fruits'>新鲜水果</li>
          <li class="main_left_li" :class="{'active':currenTab=='food'}" data-title='food'>休闲食品</li>
          <li class="main_left_li" :class="{'active':currenTab=='vegetables'}" data-title='vegetables'>时令蔬菜</li>
          <li class="main_left_li" :class="{'active':currenTab=='meat'}" data-title='meat'>肉蛋家禽</li>
      </ul>
  </div>
  <div class="main_right">
      <ul class="main_right_ul">
          <li class="main_right_li" v-for="item in items" :key="item.imgUrl">
              <img :src="item.imgUrl" alt="">
              <div class='main_right_text'>
                  <p class="main_right_title">{{item.name}}</p>
                  <p class="main_right_sv">月售{{item.sales}}件</p>
                  <p class="main_right_price"><span class="present">¥{{item.price}}</span><span class="primary">¥{{item.oldPrice}}</span></p>
              </div>
              <div class="main_right_number">
                  <span class="iconfont reduce" :class="{'none':shoppingCartSum(item._id)==0}" @click="reduce" :data-d='item._id'>&#xe8b1;</span>
                  <span class="number" :class="{'none':shoppingCartSum(item._id)==0}">{{shoppingCartSum(item._id)}}</span>
                  <span class="iconfont add" @click="add" :data-d='item._id'>&#xe728;</span>
              </div>
          </li>
      </ul>
  </div>
</template>

<script>
import { reactive, toRefs, toRaw } from '@vue/reactivity'
import { bus } from '../../assets/js/public.js'
import { onMounted } from '@vue/runtime-core'
import { useRoute } from 'vue-router'

const data = reactive({
  currenTab: 'all',
  myShoppingCart: []
})
export default {
  name: 'Main',
  emits: ['tabs'],
  props: ['items'],

  setup (props, content) {
    const items = toRaw(props.items)
    const route = useRoute()
    const shopId = route.params.id
    // 初始化数据
    init()

    // 向父组件触发自定义事件
    function tab (e) {
      const targetName = e.target.nodeName
      const targetTitle = e.target.dataset.title
      content.emit('tabs', targetName, targetTitle)
      if (e.target.nodeName === 'LI') {
        data.currenTab = targetTitle
      }
    }

    // 购物车加
    function add (e) {
      addRed(e, true)
    }
    // 购物车减
    function reduce (e) {
      addRed(e, false)
    }

    // 购物车加减函数封装
    function addRed (e, isAdd) {
      const d = e.target.dataset.d - 1
      const goodsId = items[d]._id
      const { id, index } = isId(goodsId)
      if (isAdd) {
      // eslint-disable-next-line no-unused-expressions
        id ? data.myShoppingCart[index].sum++ : (data.myShoppingCart.push(items[d]), data.myShoppingCart[data.myShoppingCart.length - 1].sum = 1, data.myShoppingCart[data.myShoppingCart.length - 1].shopId = shopId)
        localStorage.setItem(`ls${shopId}`, JSON.stringify(data.myShoppingCart))
        // // 使用总线触发自定义事件向兄弟组件传值
        bus.emit('busMain', { spgCart: 1, price: items[d].price })
      } else {
        data.myShoppingCart[index].sum--
        // eslint-disable-next-line no-unused-expressions
        data.myShoppingCart[index].sum === 0 ? data.myShoppingCart.splice(index, 1) : undefined
        data.myShoppingCart.length === 0 ? localStorage.removeItem(`ls${shopId}`) : localStorage.setItem(`ls${shopId}`, JSON.stringify(data.myShoppingCart))
        bus.emit('busMain', { spgCart: -1, price: -items[d].price })
      }
    }

    // 生命周期函数
    onMounted(() => {
      bus.emit('busMain', { spgCart: 0, price: 0 })
    })

    // 监听兄弟组件自定义的事件
    spgCartSum()

    const { currenTab, myShoppingCart } = toRefs(data)
    return { tab, add, reduce, currenTab, myShoppingCart, shoppingCartSum }
  }
}

// 数据初始化实现逻辑
function init () {
  const route = useRoute()
  const shopId = route.params.id
  if (localStorage.getItem(`ls${shopId}`)) {
    const ls = JSON.parse(localStorage.getItem(`ls${shopId}`))
    data.myShoppingCart = ls
  } else { data.myShoppingCart = [] }
}

// 通过id判断是否在购物车中存在
function isId (id) {
  const idObj = {}
  if (data.myShoppingCart.length !== 0) {
    for (const [index, value] of data.myShoppingCart.entries()) {
      if (value._id === id) {
        idObj.id = true
        idObj.index = index
        break
      } else { idObj.id = false }
    }
  } else { idObj.id = false }
  return idObj
}

// 监听兄弟组件自定义事件后要执行的逻辑
function spgCartSum () {
  bus.off('busSum')
  bus.on('busSum', ({ id, shopId, sum }) => {
    for (const [index, value] of data.myShoppingCart.entries()) {
      if (value.shopId === shopId && value._id === id) {
        value.sum = sum
        // eslint-disable-next-line no-unused-expressions
        sum === 0 ? data.myShoppingCart.splice(index, 1) : undefined
        break
      }
    }
  })
}

// 此函数被DOM插值表达式直接引用，dom节点使用了循环，所以此函数不要和其它函数封装，避免多次执行
function shoppingCartSum (id) {
  if (data.myShoppingCart.length !== 0) {
    for (let i = 0; i < data.myShoppingCart.length; i++) {
      if (data.myShoppingCart[i]._id === id) {
        return data.myShoppingCart[i].sum
      }
    }
  }
  return 0
}
</script>

<style lang="scss" scoped>
@import '../../assets/style/public.scss';
 p{
        margin: 0;
    }
.main_right{
    flex: 1;
    overflow-y: auto;
    padding: 0 .18rem 0 .16rem;
}
.main_left_ul{
    background-color: $search-color2;
    height: 100%;
    .active{
        background-color: #ffffff;
    }
}
.main_left_li{
    width: .76rem;
    height: .4rem;
    text-align: center;
    line-height: .4rem;
}
.main_right_li{
    display: flex;
    position: relative;
    padding-bottom: .12rem;
    margin-bottom: .12rem;
    border-bottom: .01rem solid $border-bottom;
    img{
        width: .68rem;
        height: .68rem;
    }
}
.main_right_text{
    margin-left: .16rem;
    overflow: hidden;
}
.main_right_title{
    font-weight: bold;
    font-size: .14rem;
    margin-top: .02rem;
    @include text-ellipsis(auto);
}
.main_right_sv{
    font-size: .12rem;
    margin: .09rem 0;
}
.main_right_price{
    .present{
        color: #E93B3B;
        margin-right: .12rem;
    }
    .primary{
        display: inline-block;
        text-decoration: line-through;
        font-size: .12rem;
        transform: scale(0.9);
    }
}
.main_right_number{
    position: absolute;
    right: 0;
    bottom: .12rem;
    .iconfont{
        font-size: .22rem;
    }
    .number{
        vertical-align: .02rem;
        margin: 0 .1rem;
    }
    .reduce{
        color:#666666;
    }
    .add{
        color: #0091FF;
    }
    .none{
    display: none;
}
}
</style>
